<?php


namespace app\api\controller\v36;


use app\api\controller\v2\Auth;
use app\common\cachemodel\Recode as RecodeModel;
use app\common\cachemodel\YearFortune;
use app\common\cachemodel\zl3\Zl3FortuneYearAnalysis;
use app\common\cachemodel\zl3\Zl3FortuneYearAnalysisIsNew;
use app\common\lib\horoscope\HoroscopeFortune;
use app\common\lib\Util;
use think\Env;
use think\response\Json;

class FortuneYearAnalysis extends Auth
{
    /**
     * 解锁 年运运势 一生起伏
     */
    public function unlockFortuneFluctuate()
    {
        $rid = input('rid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }
        $recode_info = (new RecodeModel())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }

        $unlockYears = (new YearFortune())->getReocdeFortuneUnlockYears($rid);
        $yearFortuneAnalysis = config('year_fortune_analysis.analysis');

        if (count($unlockYears) < $yearFortuneAnalysis[1]['unlock_num'])
        {
            return show(config('code.toast'), '需要解锁6年年运才可查看～');
        }

        $FortuneYearAnalysisModel = new Zl3FortuneYearAnalysis();

        $yearFortuneAnalysisReport = $FortuneYearAnalysisModel->getFortuneAnalysis($recode_info, [1]);
        $yearFortuneAnalysisReport = $yearFortuneAnalysisReport ? $yearFortuneAnalysisReport[1] : [];
        if ($yearFortuneAnalysisReport && !$yearFortuneAnalysisReport['recode_is_change'])
        {   // 之前解锁过 且档案未更新
            return show(config('code.error'), '已经计算过了，请勿重复计算～');
        }

        if ($yearFortuneAnalysisReport)
        {   // 重新计算
            $data = [
                'status' => 1,   // 计算状态 1=>计算中 2=>计算完成 3=>计算失败
                'stage_num' => $yearFortuneAnalysisReport['stage_num'] + 1,    // 计算总次数+1
                'recode_info' => json_encode($recode_info, JSON_UNESCAPED_UNICODE),  // 记录最新 档案信息  json_encode
            ];

            $res = $FortuneYearAnalysisModel->UpdateDataAndQueue($yearFortuneAnalysisReport['id'], $this->user['id'], $rid, $data);
        } else
        {   // 首次计算
            $data = [
                'uid' => $this->user['id'],
                'rid' => $rid,
                'type' => 1,    // 类型  1=>一生起伏 2=>人生阶段 3=>年运筛查
                'hash' => Util::getRecodeHashKey($recode_info),    //  Util::getRecodeHashKey($recode) 调用该方法获取
                'status' => 1,   // 计算状态 1=>计算中 2=>计算完成 3=>计算失败
                'order_num' => '',   // 订单编号
                'stageyear' => 0,    // type=2    20172026
                'stage_num' => 1,    // 2
                'recode_info' => json_encode($recode_info, JSON_UNESCAPED_UNICODE),  // 档案信息  json_encode
            ];

            $res = $FortuneYearAnalysisModel->SaveDataAndQueue($data);
        }

        if ($res)
        {
            return show(config('code.success'), '请求成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 年运运势 一生起伏
     */
    public function getFortuneFluctuate()
    {
        $rid = input('rid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }
        $year = (int)(date('Y'));
        $recode_info = (new RecodeModel())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }
        $type = 1;
        $oss = Env::get('host.photo');
        $FortuneYearAnalysisModel = new Zl3FortuneYearAnalysis();
        $yearFortuneAnalysisReport = $FortuneYearAnalysisModel->getFortuneAnalysis($recode_info, [$type]);
        $yearFortuneAnalysisReport = $yearFortuneAnalysisReport ? $yearFortuneAnalysisReport[$type] : [];
        if (!$yearFortuneAnalysisReport)
        {
            return show(config('code.error'), '服务异常，数据不存在～');
        }
        $stageFortune = [
            'tip' => '阶段运势起伏指的是你这一生大运的起伏情况',
            'tips' => '数字代表本年整体的运势概况，为正数时整体运势较好。相反为运势比较一般，仅供参考。',
        ];
        $fleetingTime = [
            'tip' => '流年起伏指的是你这一生流年的起伏情况',
            'tips' => '数字代表本年整体的运势概况，为正数时整体运势较好。相反为运势比较一般，仅供参考。',
        ];
        // 接入正式数据
        if ($yearFortuneAnalysisReport['content'])
        {   // 一生起伏结果
            $btithDayYear = (int)($yearFortuneAnalysisReport['recode_info']['year']); // 出生年
            $maxYear = 0;
            foreach ($yearFortuneAnalysisReport['content']['dayun'] as $item)
            {
                if ($item['start'] - $btithDayYear > 100)
                {   // 当前大运阶段用户 超过100岁 忽略该阶段
                    continue;
                }
//                $n = (int)(ceil($item['score'] / 5) - 10);
                $n = ceil($item['score']);
                $n = min($n, 10);
                $select = $year >= $item['start'] && $year <= $item['end'] ? 1 : 0;
                $stageFortune['curve_list'][] = [
                    'name' => sprintf("%s-%s", $item['start'], $item['end']),
                    'tips' => '人生起伏' . ($n === 0 ? 0 : sprintf("%+d", $n)),
                    'score' => $n,
                    'select' => $select,
                ];
                $maxYear = $item['end'];
            }
            foreach ($yearFortuneAnalysisReport['content']['liunian'] as $item)
            {
                if ($item['start'] > $maxYear)
                {
                    continue;
                }
//                $n = (int)(ceil($item['score'] / 5) - 10);
                $n = ceil($item['score']);
                $n = min($n, 10);
                $fleetingTime['curve_list'][] = [
                    'name' => (string)$item['start'],
                    'tips' => '流年起伏' . ($n === 0 ? 0 : sprintf("%+d", $n)),
                    'score' => $n,
                    'select' => $year === (int)$item['start'] ? 1 : 0,
                ];
            }
        }

        $recodeData = (new Util())->getFortuneDetailRecodeInfo([$yearFortuneAnalysisReport['recode_info']], $this->user['rid']);
        $unlockRecodeInfo = [
            'recode_is_change' => 0,
            'info' => $recodeData,
            'change_title' => '',
            'change_desc' => '',
            'target' => '',
            'link' => '',
            'btn_name' => '',
            'btn_status' => 0
        ];
        if ($yearFortuneAnalysisReport['recode_is_change'] === true)
        {   // 档案已更新 或者 状态在计算中 展示档案更新提示
            $unlockRecodeInfo['recode_is_change'] = 1;
            $unlockRecodeInfo['change_title'] = '检测到当前档案出生时间已发生修改';
            $unlockRecodeInfo['change_desc'] = '已计算的内容不会随着档案的修改重新计算。';
            if ($yearFortuneAnalysisReport['status'] === 1)
            {   // 计算中
                $unlockRecodeInfo['target'] = 'local';
                $unlockRecodeInfo['link'] = 'empty';
                $unlockRecodeInfo['btn_name'] = '计算中…';
            } else
            {   // 已解锁
                $host = Env::get('host.domain');
                $unlockRecodeInfo['target'] = 'api';
                $unlockRecodeInfo['link'] = $host . '/api/v36/fortune_year_analysis/unlock_fluctuate?rid=' . $rid;
                $unlockRecodeInfo['btn_name'] = '重新计算';
                $unlockRecodeInfo['btn_status'] = 1;
            }
        }

        return show(config('code.success'), '请求成功', [
            'img' => $oss . '/test/fortune/fortune_year_analysis/fluctuate_title_img.png',
            'stage_fortune' => $stageFortune,
            'fleeting_time' => $fleetingTime,
            'unlock_recode_info' => $unlockRecodeInfo,
        ]);
    }

    /**
     * 年运运势 人生阶段
     */
    public function getFortuneStage()
    {
        $rid = input('rid/d', 0);
        $year = input('year/d', 0);
        $order_id = input('order_id/s', '');
        // 当前查看的年时间戳
        $now_time = strtotime($year . '-1');
        // 参数验证
        if (!$rid || (empty($order_id) && (strlen($year) !== 4 || !$now_time)))
        {   // 订单编号为空  year字段必传
            return show(config('code.error'), '未知操作');
        }

        $recode_info = (new RecodeModel())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }
        $oss = Env::get('host.photo');
        $FortuneYearAnalysisModel = new Zl3FortuneYearAnalysis();
        if ($order_id)
        {
            $yearFortuneAnalysisReport = $FortuneYearAnalysisModel->getOrderFortuneAnalysis($this->user['id'], $rid, $order_id);
            if (!$yearFortuneAnalysisReport)
            {
                return show(config('code.error'), '服务异常，数据不存在～');
            }
            $stageyearItem = (string)$yearFortuneAnalysisReport['stageyear'];
            $sT = substr($stageyearItem, 0, 4);
            $eT = substr($stageyearItem, 4, 4);
            $arr_n = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
            $stageyearData = [
                'num' => $yearFortuneAnalysisReport['stage_num'],
                'num_han' => $arr_n[$yearFortuneAnalysisReport['stage_num']],
                'start_year' => (int)$sT,
                'end_year' => (int)$eT,
            ];
        } else
        {
            $type = 2;
            $stageyearData = Util::getRecodeStageyear($recode_info, $year);
            if ($stageyearData['num'] === 0)
            {
                return show(config('code.error'), '未知的人生阶段～');
            }
            $yearFortuneAnalysisReport = $FortuneYearAnalysisModel->getFortuneAnalysis($recode_info, [$type], $year, $stageyearData);
            $yearFortuneAnalysisReport = $yearFortuneAnalysisReport ? $yearFortuneAnalysisReport[$type] : [];
            if (!$yearFortuneAnalysisReport)
            {
                return show(config('code.error'), '服务异常，数据不存在～');
            }
        }

        $list = [];
        // 接入正式数据
        $title = '';
        if ($yearFortuneAnalysisReport['content'])
        {   // 人生阶段 结果
            $textConfig = config('renshengjieduan');
            $contentData = $yearFortuneAnalysisReport['content'];
            $title = $textConfig[$contentData['topic']['code']]['keyword'] ?? '';
            $list[] = [
                'icon' => $oss . '/test/fortune/fortune_year_analysis/stage_tip.png',
                'title' => '本部分是以十年为一阶段对运势进行总结，具体运势仍建议以每年年运为准。',
                'des' => $textConfig[$contentData['topic']['code']]['text'] ?? '',
                'type' => 0,
                'years_des' => '',
            ];
            $typeConfig = [
                '婚恋' => 1,
                '财富' => 2,
                '事业' => 3,
                '健康' => 4,
            ];
            foreach ($contentData['text_list'] as $keyCodeItemData)
            {
                $years = $keyCodeItemData['years'];
                if ($years)
                {
                    $years = array_unique($years);
                    asort($years);
                    $years = array_map(function ($v)
                    {
                        return $v . '年';
                    }, $years);
                }

                $yearsDes = $years ? '关键年份：' . implode('、', $years) : '';
                $list[] = [
                    'icon' => $textConfig[$keyCodeItemData['code']]['icon'],
                    'title' => ($textConfig[$keyCodeItemData['code']]['type'] ?? '') . '：' . ($textConfig[$keyCodeItemData['code']]['keyword'] ?? ''),
                    'des' => $textConfig[$keyCodeItemData['code']]['text'] ?? '',
                    'type' => $typeConfig[($textConfig[$keyCodeItemData['code']]['type'] ?? '未知')] ?? 5,
                    'years_des' => $yearsDes,
                ];
            }
        }

        $recodeData = (new Util())->getFortuneDetailRecodeInfo([$yearFortuneAnalysisReport['recode_info']], $this->user['rid']);
        $unlockRecodeInfo = [
            'recode_is_change' => 0,
            'info' => $recodeData,
            'change_title' => '',
            'change_desc' => '',
            'target' => '',
            'link' => '',
            'btn_name' => '',
        ];
        if ($yearFortuneAnalysisReport['recode_is_change'] === true)
        {   // 档案已更新 或者 状态在计算中 展示档案更新提示
            $unlockRecodeInfo['recode_is_change'] = 1;
            $unlockRecodeInfo['change_title'] = '检测到当前档案出生时间已发生修改';
            $unlockRecodeInfo['change_desc'] = '已计算的内容不会随着档案的修改重新计算。';
            if ($yearFortuneAnalysisReport['status'] === 1)
            {   // 计算中
                $unlockRecodeInfo['target'] = 'local';
                $unlockRecodeInfo['link'] = 'empty';
                $unlockRecodeInfo['btn_name'] = '计算中…';
            } else
            {   // 已解锁
                $unlockRecodeInfo['target'] = 'local';
                // 人生阶段 再次开通
                $unlockRecodeInfo['link'] = "pay_order?type=27&rid={$rid}&gid=91&start_time={$year}&live_id=&need_auth=1";
                $unlockRecodeInfo['btn_name'] = '再次开通';
            }
        }

        return show(config('code.success'), '请求成功', [
            'img' => $oss . '/test/fortune/fortune_year_analysis/stage_title_img.png',
            'title' => $title,
            'des' => sprintf("第%s阶段：%d年起-%d年止", $stageyearData['num_han'], $stageyearData['start_year'], $stageyearData['end_year']),
            'list' => $list,
            'unlock_recode_info' => $unlockRecodeInfo,
        ]);
    }

    /**
     * 年运运势 年运筛查
     * @return Json
     * @throws \Exception
     */
    public function getFortuneScreening()
    {
        $rid = input('rid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }
        $order_id = input('order_id/s', '');
        $nowYear = (int)(date('Y'));
        $recode_info = (new RecodeModel())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '请求异常，档案不存在～');
        }
        $FortuneYearAnalysisModel = new Zl3FortuneYearAnalysis();
        if ($order_id)
        {
            $yearFortuneAnalysisReport = $FortuneYearAnalysisModel->getOrderFortuneAnalysis($this->user['id'], $rid, $order_id);
        } else
        {
            $type = 3;
            $yearFortuneAnalysisReport = $FortuneYearAnalysisModel->getFortuneAnalysis($recode_info, [$type]);
            $yearFortuneAnalysisReport = $yearFortuneAnalysisReport ? $yearFortuneAnalysisReport[$type] : [];
        }
        if (!$yearFortuneAnalysisReport)
        {
            return show(config('code.error'), '服务异常，数据不存在～');
        }

        $screeningConfig = config('fortune.year_fortune_screening');
        $list = [];
        // 接入正式数据
        if ($yearFortuneAnalysisReport['content'])
        {   // 年运筛查 结果
            $levelConfig = [
                1 => '等级：I',
                2 => '等级：II',
                3 => '等级：III',
            ];
            foreach ($yearFortuneAnalysisReport['content'] as $itemData)
            {
                $itemData['year'] = (int)$itemData['year'];
                $list[] = [
                    'year' => $itemData['year'],
                    'title' => $screeningConfig[$itemData['type']]['title'],
                    'icon' => $screeningConfig[$itemData['type']]['icon'],
                    'type' => $itemData['type'],
                    'level' => $itemData['level'],
                    'level_des' => $levelConfig[$itemData['level']] ?? '等级：II',
                    'color' => $itemData['year'] === $nowYear ? $screeningConfig[$itemData['type']]['color'] : '#D8D8D8'
                ];
            }
        }

        $recodeData = (new Util())->getFortuneDetailRecodeInfo([$yearFortuneAnalysisReport['recode_info']], $this->user['rid']);
        $unlockRecodeInfo = [
            'recode_is_change' => 0,
            'info' => $recodeData,
            'change_title' => '',
            'change_desc' => '',
            'target' => '',
            'link' => '',
            'btn_name' => '',
        ];
        if ($yearFortuneAnalysisReport['recode_is_change'] === true)
        {   // 档案已更新 或者 状态在计算中 展示档案更新提示
            $unlockRecodeInfo['recode_is_change'] = 1;
            $unlockRecodeInfo['change_title'] = '检测到当前档案出生时间已发生修改';
            $unlockRecodeInfo['change_desc'] = '已计算的内容不会随着档案的修改重新计算。';
            if ($yearFortuneAnalysisReport['status'] === 1)
            {   // 计算中
                $unlockRecodeInfo['target'] = 'local';
                $unlockRecodeInfo['link'] = 'empty';
                $unlockRecodeInfo['btn_name'] = '计算中…';
            } else
            {   // 已解锁
                $unlockRecodeInfo['target'] = 'local';
                $unlockRecodeInfo['link'] = "pay_order?type=27&rid={$rid}&gid=92&live_id=&need_auth=1";
                $unlockRecodeInfo['btn_name'] = '再次开通';
            }
        }

        $introList = array_values($screeningConfig);

        foreach ($introList as $k => $v)
        {
            unset($introList[$k]['color']);
        }

        return show(config('code.success'), '请求成功', [
            'tip' => '只展示重点年运，等级越高影响越大。',
            'intro_list' => $introList,
            'list' => $list,
            'unlock_recode_info' => $unlockRecodeInfo,
        ]);
    }

    /**
     * 年运运势数据分析【年运首页  一生起伏｜人生阶段｜年运筛查 消息小红点】 消息已读
     * @return Json
     * @throws \Exception
     */
    public function msgRead()
    {
        $rid = input('rid/d', 0);
        $type = input('type/d', 0);
        $year = input('year/d', 0);

        if (!in_array($type, [0, 1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $type++;
        $recode_info = (new RecodeModel())->getInfoById($rid);
        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $FortuneYearAnalysisIsNewModel = new Zl3FortuneYearAnalysisIsNew();
        if ($type === 2)
        {
            $stageyear = Util::getRecodeStageyear($recode_info, $year);
            $flag = (int)($stageyear['start_year'] . $stageyear['end_year']);
        } else
        {
            $flag = 0;
        }
        $FortuneYearAnalysisIsNewModel->setNewStatus($this->user['id'], $rid, $type, $flag, 0);

        return show(config('code.success'), '请求成功');
    }
}
